package org.domain.sisteste.session.dao;

import java.util.List;

import javax.persistence.EntityManager;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.CriteriaSpecification;
import org.jboss.seam.annotations.In;

/**
 * @author hugoalexandre
 *
 * @param <T>
 */
public class GenericDAO<T> implements DAO<T> {

	@In
	private EntityManager entityManager;

	private Class<T> classe;

	public GenericDAO(Class<T> classe) {
		this.classe = classe;
	}

	protected Session getSession() {
		return (Session) entityManager.getDelegate();
	}

	@SuppressWarnings("unchecked")
	public T load(Integer id) {
		T object = (T) getSession().get(classe, id);
		return object;
	}

	public void remove(T obj) {
		getSession().delete(obj);
		getSession().flush();

	}

	@SuppressWarnings("unchecked")
	public List<T> retriveAll() {
		Criteria criteria = getSession().createCriteria(classe);
		criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
		return criteria.list();
	}

	public void save(T obj) {
		getSession().save(obj);
		getSession().flush();

	}

	public void update(T obj) {
		getSession().update(obj);
		getSession().flush();
	}

	public void saveOrUpdate(T obj) {
		getSession().saveOrUpdate(obj);
		getSession().flush();
	}

}

